use clap::{Parser, Subcommand};
use colored::*;
use std::fs;
use std::path::Path;
use walkdir::WalkDir;
use indicatif::ProgressBar;
use serde_json;
use csv;
use regex::Regex;
use uuid::Uuid;
use rand::Rng;
use hex;
use md5;
use sha2::{Sha256, Sha512, Digest};
use base64::{Engine as _, engine::general_purpose};
use sysinfo::System;
use zip::write::FileOptions;

/// 高级 Rust CLI 工具 - 展示 Rust 在命令行工具开发中的强大能力
/// 包括：文件操作、文本处理、数据处理、系统监控、实用工具等

#[derive(Parser)]
#[command(name = "rust-cli-pro")]
#[command(about = "一个功能强大的Rust CLI工具演示 (专业版)")]
#[command(version = "2.0.0")]
struct Cli {
    /// 启用详细输出
    #[arg(short, long)]
    verbose: bool,
    
    /// 启用彩色输出
    #[arg(short, long)]
    color: bool,
    
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// 文件操作命令 (统计, 搜索, 压缩, 解压, 复制, 移动, 删除)
    File {
        #[command(subcommand)]
        action: FileCommands,
    },
    /// 文本处理命令 (统计, 搜索替换, 格式化, 高亮)
    Text {
        #[command(subcommand)]
        action: TextCommands,
    },
    /// 数据处理命令 (CSV, JSON 转换与查询)
    Data {
        #[command(subcommand)]
        action: DataCommands,
    },
    /// 系统监控命令 (信息, 进程, 性能)
    System {
        #[command(subcommand)]
        action: SystemCommands,
    },
    /// 实用工具命令 (UUID, 编码, 哈希, 密码)
    Utils {
        #[command(subcommand)]
        action: UtilsCommands,
    },
}

#[derive(Subcommand)]
enum FileCommands {
    /// 文件统计信息
    Stats {
        /// 目标路径
        path: String,
        /// 递归搜索
        #[arg(short, long)]
        recursive: bool,
    },
    /// 搜索文件
    Search {
        /// 搜索模式
        pattern: String,
        /// 搜索路径
        path: String,
        /// 递归搜索
        #[arg(short, long)]
        recursive: bool,
    },
    /// 压缩文件
    Compress {
        /// 源文件或目录
        source: String,
        /// 输出文件
        output: String,
    },
    /// 解压文件
    Decompress {
        /// 压缩文件
        archive: String,
        /// 输出目录
        output: String,
    },
}

#[derive(Subcommand)]
enum TextCommands {
    /// 文本统计
    Count {
        /// 文件路径
        file: String,
    },
    /// 搜索替换
    Replace {
        /// 文件路径
        file: String,
        /// 搜索模式
        pattern: String,
        /// 替换文本
        replacement: String,
    },
    /// 格式化JSON
    Format {
        /// 文件路径
        file: String,
    },
}

#[derive(Subcommand)]
enum DataCommands {
    /// CSV处理
    Csv {
        /// 操作类型
        #[command(subcommand)]
        action: CsvCommands,
    },
    /// JSON处理
    Json {
        /// 操作类型
        #[command(subcommand)]
        action: JsonCommands,
    },
}

#[derive(Subcommand)]
enum CsvCommands {
    /// 查看CSV内容
    View {
        /// CSV文件路径
        file: String,
        /// 显示行数
        #[arg(short, long, default_value = "10")]
        rows: usize,
    },
    /// 转换CSV到JSON
    ToJson {
        /// CSV文件路径
        file: String,
        /// 输出文件
        #[arg(short, long)]
        output: Option<String>,
    },
}

#[derive(Subcommand)]
enum JsonCommands {
    /// 查看JSON内容
    View {
        /// JSON文件路径
        file: String,
    },
    /// 格式化JSON
    Format {
        /// JSON文件路径
        file: String,
    },
}

#[derive(Subcommand)]
enum SystemCommands {
    /// 系统信息
    Info {
        /// 显示详细信息
        #[arg(short, long)]
        detailed: bool,
    },
    /// 进程列表
    Processes {
        /// 显示进程数量
        #[arg(short, long, default_value = "20")]
        count: usize,
    },
    /// 系统监控
    Monitor {
        /// 监控间隔(秒)
        #[arg(short, long, default_value = "1")]
        interval: u64,
    },
}

#[derive(Subcommand)]
enum UtilsCommands {
    /// 生成UUID
    Uuid {
        /// 生成数量
        #[arg(short, long, default_value = "1")]
        count: usize,
    },
    /// 编码转换
    Encode {
        /// 文本内容
        text: String,
        /// 编码类型 (base64, hex, url)
        #[arg(short, long, default_value = "base64")]
        type_: String,
    },
    /// 解码转换
    Decode {
        /// 编码文本
        text: String,
        /// 编码类型 (base64, hex, url)
        #[arg(short, long, default_value = "base64")]
        type_: String,
    },
    /// 计算哈希
    Hash {
        /// 文件路径
        file: String,
        /// 哈希算法 (md5, sha256, sha512)
        #[arg(short, long, default_value = "sha256")]
        algorithm: String,
    },
    /// 生成密码
    Password {
        /// 密码长度
        #[arg(short, long, default_value = "16")]
        length: usize,
        /// 包含特殊字符
        #[arg(short, long)]
        special: bool,
    },
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();
    
    // 设置彩色输出
    if cli.color {
        colored::control::set_override(true);
    }
    
    match cli.command {
        Commands::File { action } => handle_file_commands(action, cli.verbose)?,
        Commands::Text { action } => handle_text_commands(action, cli.verbose)?,
        Commands::Data { action } => handle_data_commands(action, cli.verbose)?,
        Commands::System { action } => handle_system_commands(action, cli.verbose)?,
        Commands::Utils { action } => handle_utils_commands(action, cli.verbose)?,
    }
    
    Ok(())
}

fn handle_file_commands(command: FileCommands, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        FileCommands::Stats { path, recursive } => {
            file_stats(&path, recursive, verbose)?;
        },
        FileCommands::Search { pattern, path, recursive } => {
            search_files(&pattern, &path, recursive, verbose)?;
        },
        FileCommands::Compress { source, output } => {
            compress_file(&source, &output, verbose)?;
        },
        FileCommands::Decompress { archive, output } => {
            decompress_file(&archive, &output, verbose)?;
        },
    }
    Ok(())
}

fn handle_text_commands(command: TextCommands, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        TextCommands::Count { file } => {
            text_count(&file, verbose)?;
        },
        TextCommands::Replace { file, pattern, replacement } => {
            text_replace(&file, &pattern, &replacement, verbose)?;
        },
        TextCommands::Format { file } => {
            format_json(&file, verbose)?;
        },
    }
    Ok(())
}

fn handle_data_commands(command: DataCommands, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        DataCommands::Csv { action } => {
            match action {
                CsvCommands::View { file, rows } => {
                    csv_view(&file, rows, verbose)?;
                },
                CsvCommands::ToJson { file, output } => {
                    csv_to_json(&file, output.as_deref(), verbose)?;
                },
            }
        },
        DataCommands::Json { action } => {
            match action {
                JsonCommands::View { file } => {
                    json_view(&file, verbose)?;
                },
                JsonCommands::Format { file } => {
                    json_format(&file, verbose)?;
                },
            }
        },
    }
    Ok(())
}

fn handle_system_commands(command: SystemCommands, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        SystemCommands::Info { detailed } => {
            system_info(detailed, verbose)?;
        },
        SystemCommands::Processes { count } => {
            list_processes(count, verbose)?;
        },
        SystemCommands::Monitor { interval } => {
            system_monitor(interval, verbose)?;
        },
    }
    Ok(())
}

fn handle_utils_commands(command: UtilsCommands, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        UtilsCommands::Uuid { count } => {
            generate_uuids(count, verbose)?;
        },
        UtilsCommands::Encode { text, type_ } => {
            encode_text(&text, &type_, verbose)?;
        },
        UtilsCommands::Decode { text, type_ } => {
            decode_text(&text, &type_, verbose)?;
        },
        UtilsCommands::Hash { file, algorithm } => {
            calculate_hash(&file, &algorithm, verbose)?;
        },
        UtilsCommands::Password { length, special } => {
            generate_password(length, special, verbose)?;
        },
    }
    Ok(())
}

// 文件操作函数
fn file_stats(path: &str, recursive: bool, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let pb = ProgressBar::new_spinner();
    pb.set_message("分析文件...");
    
    let mut total_files = 0;
    let mut total_dirs = 0;
    let mut total_size = 0;
    let mut file_types = std::collections::HashMap::new();
    
    let walker = if recursive {
        WalkDir::new(path).into_iter()
    } else {
        WalkDir::new(path).max_depth(1).into_iter()
    };
    
    for entry in walker.filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            total_files += 1;
            if let Ok(metadata) = entry.metadata() {
                total_size += metadata.len();
            }
            
            if let Some(ext) = entry.path().extension() {
                let ext_str = ext.to_string_lossy().to_lowercase();
                *file_types.entry(ext_str).or_insert(0) += 1;
            }
        } else if entry.file_type().is_dir() {
            total_dirs += 1;
        }
        
        pb.tick();
    }
    
    pb.finish_with_message("✅ 分析完成");
    
    println!("📊 文件统计:");
    println!("  路径: {}", path.blue());
    println!("  文件数: {}", total_files.to_string().green());
    println!("  目录数: {}", total_dirs.to_string().green());
    println!("  总大小: {}", format_bytes(total_size).yellow());
    
    if !file_types.is_empty() {
        println!("  文件类型分布:");
        let mut sorted_types: Vec<_> = file_types.iter().collect();
        sorted_types.sort_by(|a, b| b.1.cmp(a.1));
        for (ext, count) in sorted_types.iter().take(10) {
            println!("    .{}: {} 个文件", ext, count);
        }
    }
    
    Ok(())
}

fn search_files(pattern: &str, path: &str, recursive: bool, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let pb = ProgressBar::new_spinner();
    pb.set_message("搜索文件...");
    
    let regex = Regex::new(pattern)?;
    let mut matches = Vec::new();
    
    let walker = if recursive {
        WalkDir::new(path).into_iter()
    } else {
        WalkDir::new(path).max_depth(1).into_iter()
    };
    
    for entry in walker.filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            if let Some(filename) = entry.file_name().to_str() {
                if regex.is_match(filename) {
                    matches.push(entry.path().to_string_lossy().to_string());
                }
            }
        }
        pb.tick();
    }
    
    pb.finish_with_message("✅ 搜索完成");
    
    println!("🔍 搜索结果 (模式: {}):", pattern.blue());
    if matches.is_empty() {
        println!("  没有找到匹配的文件");
    } else {
        for file in matches {
            println!("  {}", file.green());
        }
    }
    
    Ok(())
}

fn compress_file(source: &str, output: &str, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let pb = ProgressBar::new_spinner();
    pb.set_message("压缩文件...");
    
    let file = std::fs::File::create(output)?;
    let mut zip = zip::ZipWriter::new(file);
    let options = FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
    
    let source_path = Path::new(source);
    if source_path.is_file() {
        zip.start_file(source_path.file_name().unwrap().to_string_lossy(), options)?;
        let mut file = std::fs::File::open(source)?;
        std::io::copy(&mut file, &mut zip)?;
    } else if source_path.is_dir() {
        for entry in WalkDir::new(source) {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                let relative_path = path.strip_prefix(source)?;
                zip.start_file(relative_path.to_string_lossy(), options)?;
                let mut file = std::fs::File::open(path)?;
                std::io::copy(&mut file, &mut zip)?;
            }
        }
    }
    
    zip.finish()?;
    pb.finish_with_message("✅ 压缩完成");
    
    println!("📦 压缩完成:");
    println!("  源: {}", source.blue());
    println!("  输出: {}", output.green());
    
    Ok(())
}

fn decompress_file(archive: &str, output: &str, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let pb = ProgressBar::new_spinner();
    pb.set_message("解压文件...");
    
    let file = std::fs::File::open(archive)?;
    let mut zip_archive = zip::ZipArchive::new(file)?;
    
    std::fs::create_dir_all(output)?;
    
    for i in 0..zip_archive.len() {
        let mut file = zip_archive.by_index(i)?;
        let outpath = Path::new(output).join(file.name());
        
        if file.name().ends_with('/') {
            std::fs::create_dir_all(&outpath)?;
        } else {
            if let Some(p) = outpath.parent() {
                std::fs::create_dir_all(p)?;
            }
            let mut outfile = std::fs::File::create(&outpath)?;
            std::io::copy(&mut file, &mut outfile)?;
        }
        pb.tick();
    }
    
    pb.finish_with_message("✅ 解压完成");
    
    println!("📦 解压完成:");
    println!("  源: {}", archive.blue());
    println!("  输出: {}", output.green());
    
    Ok(())
}

// 文本处理函数
fn text_count(file: &str, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let contents = fs::read_to_string(file)?;
    let lines = contents.lines().count();
    let words = contents.split_whitespace().count();
    let chars = contents.chars().count();
    let bytes = contents.len();
    
    println!("📝 文本统计:");
    println!("  文件: {}", file.blue());
    println!("  行数: {}", lines.to_string().green());
    println!("  单词数: {}", words.to_string().green());
    println!("  字符数: {}", chars.to_string().green());
    println!("  字节数: {}", bytes.to_string().green());
    
    Ok(())
}

fn text_replace(file: &str, pattern: &str, replacement: &str, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let contents = fs::read_to_string(file)?;
    let regex = Regex::new(pattern)?;
    let new_contents = regex.replace_all(&contents, replacement);
    
    if new_contents != contents {
        fs::write(file, new_contents.as_bytes())?;
        println!("✅ 替换完成:");
        println!("  文件: {}", file.blue());
        println!("  模式: {}", pattern.yellow());
        println!("  替换: {}", replacement.green());
    } else {
        println!("ℹ️  没有找到匹配的内容");
    }
    
    Ok(())
}

fn format_json(file: &str, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let contents = fs::read_to_string(file)?;
    let json_value: serde_json::Value = serde_json::from_str(&contents)?;
    let formatted = serde_json::to_string_pretty(&json_value)?;
    
    fs::write(file, formatted)?;
    println!("✅ JSON格式化完成: {}", file.blue());
    
    Ok(())
}

// 数据处理函数
fn csv_view(file: &str, rows: usize, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut rdr = csv::Reader::from_path(file)?;
    let headers = rdr.headers()?.clone();
    
    println!("📊 CSV内容 (显示前{}行):", rows);
    println!("  文件: {}", file.blue());
    
    // 打印表头
    for (i, header) in headers.iter().enumerate() {
        if i > 0 { print!(" | "); }
        print!("{}", header.bold());
    }
    println!();
    println!("{}", "-".repeat(50));
    
    // 打印数据行
    for (i, result) in rdr.records().enumerate() {
        if i >= rows { break; }
        let record = result?;
        for (j, field) in record.iter().enumerate() {
            if j > 0 { print!(" | "); }
            print!("{}", field);
        }
        println!();
    }
    
    Ok(())
}

fn csv_to_json(file: &str, output: Option<&str>, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut rdr = csv::Reader::from_path(file)?;
    let mut records = Vec::new();
    
    for result in rdr.records() {
        let record = result?;
        let mut json_record = std::collections::HashMap::new();
        for (i, field) in record.iter().enumerate() {
            json_record.insert(format!("field_{}", i), field.to_string());
        }
        records.push(json_record);
    }
    
    let json = serde_json::to_string_pretty(&records)?;
    let output_file = match output {
        Some(path) => path.to_string(),
        None => format!("{}.json", file),
    };
    fs::write(&output_file, json)?;
    
    println!("✅ CSV转JSON完成:");
    println!("  源: {}", file.blue());
    println!("  输出: {}", output_file.green());
    
    Ok(())
}

fn json_view(file: &str, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let contents = fs::read_to_string(file)?;
    let json_value: serde_json::Value = serde_json::from_str(&contents)?;
    
    println!("📄 JSON内容:");
    println!("  文件: {}", file.blue());
    println!("{}", serde_json::to_string_pretty(&json_value)?);
    
    Ok(())
}

fn json_format(file: &str, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let contents = fs::read_to_string(file)?;
    let json_value: serde_json::Value = serde_json::from_str(&contents)?;
    let formatted = serde_json::to_string_pretty(&json_value)?;
    
    fs::write(file, formatted)?;
    println!("✅ JSON格式化完成: {}", file.blue());
    
    Ok(())
}

// 系统监控函数
fn system_info(detailed: bool, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut sys = System::new_all();
    sys.refresh_all();
    
    println!("🖥️  系统信息:");
    println!("  操作系统: {}", std::env::consts::OS.blue());
    println!("  架构: {}", std::env::consts::ARCH.blue());
    
    let total_memory = sys.total_memory();
    let used_memory = sys.used_memory();
    let free_memory = sys.free_memory();
    
    println!("  内存:");
    println!("    总计: {}", format_bytes(total_memory).green());
    println!("    已用: {} ({:.1}%)", format_bytes(used_memory), 
        (used_memory as f64 / total_memory as f64) * 100.0);
    println!("    可用: {} ({:.1}%)", format_bytes(free_memory),
        (free_memory as f64 / total_memory as f64) * 100.0);
    
    let cpu_count = sys.cpus().len();
    let cpu_usage = sys.global_cpu_info().cpu_usage();
    
    println!("  CPU:");
    println!("    核心数: {}", cpu_count.to_string().green());
    println!("    使用率: {:.1}%", cpu_usage);
    
    if detailed {
        println!("  进程数: {}", sys.processes().len());
    }
    
    Ok(())
}

fn list_processes(count: usize, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut sys = System::new_all();
    sys.refresh_all();
    
    let mut processes: Vec<_> = sys.processes().iter().collect();
    processes.sort_by(|a, b| b.1.cpu_usage().partial_cmp(&a.1.cpu_usage()).unwrap());
    
    println!("📋 进程列表 (前{}个):", count);
    println!("{:<8} {:<20} {:<8} {:<8} {}", 
        "PID", "名称", "CPU%", "内存%", "状态");
    println!("{}", "-".repeat(60));
    
    for (pid, process) in processes.iter().take(count) {
        let memory_usage = process.memory();
        let memory_percent = if sys.total_memory() > 0 {
            (memory_usage as f64 / sys.total_memory() as f64) * 100.0
        } else {
            0.0
        };
        
        println!("{:<8} {:<20} {:<8.1} {:<8.1} {}", 
            pid.as_u32(),
            truncate_string(&process.name(), 20),
            process.cpu_usage(),
            memory_percent,
            if process.status() == sysinfo::ProcessStatus::Run { "运行" } else { "其他" }
        );
    }
    
    Ok(())
}

fn system_monitor(interval: u64, _verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    println!("📊 系统监控 (按Ctrl+C停止)");
    println!("================================");
    
    let mut sys = System::new_all();
    let mut _count = 0;
    
    loop {
        sys.refresh_all();
        
        let cpu_usage = sys.global_cpu_info().cpu_usage();
        let total_memory = sys.total_memory();
        let used_memory = sys.used_memory();
        let memory_percent = (used_memory as f64 / total_memory as f64) * 100.0;
        
        let timestamp = chrono::Utc::now().format("%H:%M:%S");
        println!("[{}] CPU: {:.1}% | 内存: {:.1}% | 进程: {}", 
            timestamp, cpu_usage, memory_percent, sys.processes().len());
        
        std::thread::sleep(std::time::Duration::from_secs(interval));
        _count += 1;
    }
}

// 实用工具函数
fn generate_uuids(count: usize, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    println!("🆔 生成 UUID:");
    
    for i in 0..count {
        let uuid = Uuid::new_v4();
        println!("  {}", uuid.to_string().green());
        
        if verbose && i < 5 {
            println!("    版本: {:?}", uuid.get_version());
        }
    }
    
    Ok(())
}

fn encode_text(text: &str, type_: &str, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let encoded = match type_ {
        "base64" => general_purpose::STANDARD.encode(text.as_bytes()),
        "hex" => hex::encode(text.as_bytes()),
        "url" => urlencoding::encode(text).to_string(),
        _ => return Err("不支持的编码类型".into()),
    };
    
    println!("🔤 编码结果:");
    println!("  原始: {}", text.blue());
    println!("  编码: {}", encoded.green());
    
    if verbose {
        println!("  类型: {}", type_);
        println!("  原始长度: {} 字符", text.len());
        println!("  编码长度: {} 字符", encoded.len());
    }
    
    Ok(())
}

fn decode_text(text: &str, type_: &str, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let decoded = match type_ {
        "base64" => {
            let bytes = general_purpose::STANDARD.decode(text)?;
            String::from_utf8(bytes)?
        },
        "hex" => {
            let bytes = hex::decode(text)?;
            String::from_utf8(bytes)?
        },
        "url" => {
            urlencoding::decode(text)?.to_string()
        },
        _ => return Err("不支持的解码类型".into()),
    };
    
    println!("🔤 解码结果:");
    println!("  编码: {}", text.blue());
    println!("  解码: {}", decoded.green());
    
    if verbose {
        println!("  类型: {}", type_);
        println!("  编码长度: {} 字符", text.len());
        println!("  解码长度: {} 字符", decoded.len());
    }
    
    Ok(())
}

fn calculate_hash(file: &str, algorithm: &str, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let contents = fs::read(file)?;
    let hash = match algorithm {
        "md5" => {
            let digest = md5::compute(&contents);
            format!("{:x}", digest)
        },
        "sha256" => {
            let mut hasher = Sha256::new();
            hasher.update(&contents);
            format!("{:x}", hasher.finalize())
        },
        "sha512" => {
            let mut hasher = Sha512::new();
            hasher.update(&contents);
            format!("{:x}", hasher.finalize())
        },
        _ => return Err("不支持的哈希算法".into()),
    };
    
    println!("🔐 {} 哈希值:", algorithm.to_uppercase().blue());
    println!("  {}", hash.green());
    
    if verbose {
        println!("  文件: {}", file.blue());
        println!("  大小: {} 字节", contents.len());
        println!("  算法: {}", algorithm);
    }
    
    Ok(())
}

fn generate_password(length: usize, special: bool, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    let mut rng = rand::thread_rng();
    let mut charset = String::from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    
    if special {
        charset.push_str("!@#$%^&*()_+-=[]{}|;:,.<>?");
    }
    
    let password: String = (0..length)
        .map(|_| charset.chars().nth(rng.gen_range(0..charset.len())).unwrap())
        .collect();
    
    println!("🔐 生成的密码:");
    println!("  {}", password.green());
    
    if verbose {
        let entropy = (charset.len() as f64).log2() * length as f64;
        println!("  长度: {} 字符", length);
        println!("  字符集大小: {}", charset.len());
        println!("  熵值: {:.2} 位", entropy);
        println!("  强度: {}", if entropy >= 80.0 { "强" } else if entropy >= 60.0 { "中等" } else { "弱" });
    }
    
    Ok(())
}

// 辅助函数
fn format_bytes(bytes: u64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
    let mut size = bytes as f64;
    let mut unit_index = 0;
    
    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
        size /= 1024.0;
        unit_index += 1;
    }
    
    format!("{:.2} {}", size, UNITS[unit_index])
}

fn truncate_string(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}